<template>
    <div class="sys-search">

        <el-form :model="searchForm" :label-position="$store.labelPosition" label-width="20%">
            <el-col :xs="23" :sm="14">
            <el-form-item label="报价单号：" >
                <el-input v-model="searchForm.quotNo" placeholder="请输入报价单号"></el-input>
            </el-form-item>

            <el-form-item label="时间范围：">
                <el-col :span="11">
                    <el-date-picker type="date" placeholder="开始日期" v-model="searchForm.fromDate"
                        value-format="yyyy-MM-dd" format="yyyy-MM-dd" clearable style="width: 100%;"></el-date-picker>
                </el-col>
                <el-col class="centerText" :span="2">-</el-col>
                <el-col :span="11">
                    <el-date-picker type="date" placeholder="结束时间" v-model="searchForm.toDate"
                        value-format="yyyy-MM-dd" format="yyyy-MM-dd" clearable style="width: 100%;"></el-date-picker>
                </el-col>
            </el-form-item>

            <el-form-item label="客户：">
                <el-select v-model="searchForm.custId" clearable filterable placeholder="请选择客户" style="width: 100%;">
                    <el-option v-for="cust in customers" :key="cust.id"
                               :label="cust.name" :value="cust.id"></el-option>
                </el-select>
            </el-form-item>

            <el-form-item label="业务员：" v-if="showSells">
                <el-select v-model="searchForm.sellMan" clearable placeholder="请选择业务员" style="width: 100%;">
                    <el-option v-for="sm in sells" :key="sm.userId"
                               :label="sm.username" :value="sm.userId">
                    </el-option>
                </el-select>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" icon="el-icon-search" @click="searchQuotsByCriteria()">查询</el-button>
                <el-button type="edit" icon="el-icon-plus" @click="gotoAddQuot()">添加</el-button>
                <el-button type="danger" icon="el-icon-delete" @click="deleteQuots()">删除</el-button>

            </el-form-item>
            </el-col>
        </el-form>

        <table-mixin pagination paginationAlign="left" :paginationTotal="paginationTotal"
                     :pageChange="pageChange">
        <el-table v-loading="tableData.loading" :data="tableData.body"
                  @selection-change="handleSelectionChange" stripe border style="width:100%">
            <el-table-column type="selection"  align="center" width="40"></el-table-column>

            <el-table-column label="报价单号" prop="quotNo" min-width="10%"></el-table-column>
            <el-table-column label="日期" prop="quotDtStr" min-width="10%"></el-table-column>
            <el-table-column label="金额" prop="totalPriceStr" min-width="10%"
                             align="right" header-align="center"></el-table-column>
            <el-table-column label="客户" prop="custName" min-width="30%" ></el-table-column>
            <el-table-column label="业务员" prop="sellName" min-width="8%" ></el-table-column>

            <el-table-column label="操作" class-name="centerCell" min-width="22%">
                <template slot-scope="scope">
                    <el-button type="edit" size="small" icon="el-icon-edit" v-if="scope.row.convertFlag === 0"
                        @click="gotoEditQuot(scope.row.id)">编辑</el-button>
                    <el-button type="edit" size="small" icon="fa fa-exchange" v-if="scope.row.convertFlag === 0"
                               @click="convertQuot(scope.row.id)">转成订单</el-button>
                    <el-button type="primary" size="small" icon="el-icon-view"
                        @click="gotoViewQuot(scope.row.id)">查看</el-button>
                </template>
            </el-table-column>
        </el-table>
        </table-mixin>

    </div>
</template>

<script>
import { mapState } from 'vuex'

export default {
    name: "QuotSearch",
    data() {
        return {
            searchForm: {
                quotNo: '',
                fromDate: '',
                toDate: '',
                custId: '',
                sellMan: ''
            },

            tableData: {
                loading: true,
                body: []
            },
            currentPage: 1,
            paginationTotal: 0,
            selectedQuots: []
        }
    },

    mounted() {
        this.searchQuotsByCriteria()
    },

    methods: {
        searchQuotsByCriteria(){
            this.currentPage = 1;
            this.searchQuot();
        },

        // 获取table数据
        async searchQuot() {
            console.log("this.currentPage: ", this.currentPage);
            let res = await this.$axios.post('/sell/quot/list', {
                pageSize: this.$store.state.pageSize,
                pageNo: this.currentPage,
                quotNo: this.searchForm.quotNo,
                fromDate: this.searchForm.fromDate,
                toDate: this.searchForm.toDate,
                custId: this.searchForm.custId,
                sellMan: this.searchForm.sellMan
            });

            console.log("返回报价列表：", res);
            this.tableData.loading = false;
            this.tableData.body = res.rows;
            this.paginationTotal = res.total;
        },

        pageChange(currentPage) {
            console.log(`当前第${currentPage}页`)
            this.currentPage = currentPage;
            this.searchQuot();
        },

        gotoAddQuot(){
            this.$store.dispatch('quot/showEditQuot', -1)
        },

        gotoEditQuot(quotId) {
            this.$store.dispatch('quot/showEditQuot', quotId)
        },

        async convertQuot(quotId) {
            console.log(`converted quotId: ${quotId}`);
            let res = await this.$axios.put(`/sell/quot/convert/${quotId}`);
            /*console.log("转化后的订单主键：", res.result);
            let quot = this.tableData.body.find((value, index, arr) => {
                console.log(`value is ${value}`);
                console.log(`value.id is ${value.id}`);
                value.id == quotId;
            });
            //quot.convertFlag = 1;
            console.log("find quot: ", quot)*/
            this.searchQuot();
            this.$router.push("/sell/order")
        },

        gotoViewQuot(quotId) {
            this.$store.dispatch('quot/showViewQuot', quotId)
        },

        handleSelectionChange(val) {
            console.log("选中的元素: ", val); // val 中是所有选中的元素的值
            this.selectedQuots = val
        },

        deleteQuots(){
            if(this.selectedQuots.length === 0){
                this.$myMsg.warning("请选择要删除的报价")
                return;
            }

            this.$confirm('确实要删除选中的报价吗？', '确认信息', {
                distinguishCancelAndClose: true,
                confirmButtonText: '确定',
                cancelButtonText: '取消'
            })
            .then(() => {
                this.actualDeleteQuots();
            })
            .catch(action => {
                this.$myMsg.info('已放弃删除选中的报价。');
            });
        },

        async actualDeleteQuots(){
            let quotIds = [];
            for(let tmpQuot of this.selectedQuots){
                quotIds.push(tmpQuot.id)
            }

            await this.$axios.delete('/sell/quot', quotIds);
            this.$myMsg.success('删除成功');
            quotIds = [];
            this.searchQuotsByCriteria();
            this.selectedQuots=[]
        }
    },

    computed: {
        ...mapState({
            customers: state => state.quot.initPageData.customers,
            sells: state => state.quot.initPageData.sells,
            showSells: state => state.quot.initPageData.showSells
        })
    }
}
</script>

